/*
 *    Copyright 2024-2025, Warm-Flow (290631660@qq.com).
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.dromara.warm.flow.orm.dao;

import org.beetl.sql.core.page.DefaultPageRequest;
import org.beetl.sql.core.page.PageRequest;
import org.beetl.sql.core.page.PageResult;
import org.beetl.sql.core.query.LambdaQuery;
import org.beetl.sql.core.query.Query;
import org.beetl.sql.mapper.MapperJava8Proxy;
import org.dromara.warm.flow.core.entity.RootEntity;
import org.dromara.warm.flow.core.orm.agent.WarmQuery;
import org.dromara.warm.flow.core.orm.dao.WarmDao;
import org.dromara.warm.flow.core.utils.ObjectUtil;
import org.dromara.warm.flow.core.utils.StringUtils;
import org.dromara.warm.flow.core.utils.page.Page;
import org.dromara.warm.flow.orm.entity.FlowUser;
import org.dromara.warm.flow.orm.mapper.WarmMapper;
import org.dromara.warm.flow.orm.utils.TenantDeleteUtil;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * BaseMapper接口
 *
 * @author warm
 * @since 2023-03-17
 */
public abstract class WarmDaoImpl<T extends RootEntity> implements WarmDao<T> {

    public abstract WarmMapper<T> getMapper();


    /**
     * 根据id查询
     *
     * @param id 主键
     * @return 实体
     */
    @Override
    public T selectById(Serializable id) {
        return getMapper().single(id);
    }

    /**
     * 根据ids查询
     *
     * @param ids 主键
     * @return 实体
     */
    @Override
    public List<T> selectByIds(Collection<? extends Serializable> ids) {
        return getMapper().selectByIds((List<?>) ids);
    }

    @Override
    public Page<T> selectPage(T entity, Page<T> page) {
        TenantDeleteUtil.fillEntity( entity);
        DefaultPageRequest<T> request = new DefaultPageRequest<>();
        request.setTotalRequired(true);
        request.setListRequired(true);
        request.setPageNumber(page.getPageNum());
        request.setPageSize(page.getPageSize());
        request.setOrderBy(page.getOrderBy());
        PageResult<T> pageResult = getMapper().listPage(request, entity);
        Page<T> pageT = new Page<>(pageResult.getList(), pageResult.getTotalRow());
        pageT.setPageNum(page.getPageNum());
        pageT.setPageSize(page.getPageSize());
        return pageT;
    }

    @Override
    public List<T> selectList(T entity, WarmQuery<T> query) {
//        LambdaQuery<T> lambdaQuery = getMapper().createLambdaQuery();
//        if (ObjectUtil.isNotNull(query) && StringUtils.isNotEmpty(query.getOrderBy())) {
//            if (query.getIsAsc().equals("ASC")) {
//                lambdaQuery.asc(query.getOrderBy());
//            } else {
//                lambdaQuery.desc(query.getOrderBy());
//            }
//        }
        return getMapper().template(entity);
    }

    @Override
    public long selectCount(T entity) {
        return getMapper().templateCount(entity);
    }

    @Override
    public int save(T entity) {
        TenantDeleteUtil.fillEntity(entity);
        return getMapper().createLambdaQuery().insertSelective(entity);
    }

    @Override
    public int updateById(T entity) {
        LambdaQuery<T> lambdaQuery = getMapper().createLambdaQuery();
        TenantDeleteUtil.getIdWrapper(lambdaQuery, entity.getId());
        lambdaQuery.andEq(T::getId, entity.getId());
        return lambdaQuery.updateSelective(entity);
    }

    @Override
    public int delete(T entity) {
        return getMapper().getSQLManager().lambdaQuery(entity.getClass()).delete();
//        Class target = entity.getClass();
//        SQLExecutor script = getMapper().getSQLManager().getScript(target, AutoSQLEnum.DELETE_TEMPLATE_BY_ID);
//        return script.update(target, entity);
    }

    @Override
    public int deleteById(Serializable id) {
        return getMapper().deleteById(id);
    }

    @Override
    public int deleteByIds(Collection<? extends Serializable> ids) {
        return getMapper().createLambdaQuery().andIn(T::getId, ids).delete();
//        Table table = newEntity().getClass().getAnnotation(Table.class);
//        String tabName = table.name();
//        String sql = "delete from "+tabName+" where id in ( #{join(ids)} )";
//        Map paras = new HashMap();
//        paras.put("ids", ids);
//        return getMapper().getSQLManager().executeUpdate(sql, paras);
    }

    @Override
    public void saveBatch(List<T> list) {
        list.stream().forEach(item -> item.setDelFlag("0"));
        getMapper().insertBatch(list);
    }

    @Override
    public void updateBatch(List<T> list) {
        getMapper().updateByIdBatch(list);
    }

}
